package chen.web.controller;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import chen.web.config.ConfigRepository;
import chen.web.config.EmailConfig;
import chen.web.config.SiteConfig;
import chen.web.controller.forum.JSONResponse;
import chen.web.controller.forum.form.EmailAccountForm;
import chen.web.controller.forum.form.SiteConfigForm;
import chen.web.email.EmailAddress;
import chen.web.email.EmailSender;
import chen.web.email.SimpleEmail;

@Controller
public class SystemConfigController {

	private @Autowired Validator validator;
	private @Autowired EmailSender sender;
	
	//保存邮箱配置
	@RequestMapping(value="/config/emailAccount", method=RequestMethod.POST)
	public @ResponseBody JSONResponse saveEmailAccount(@RequestBody EmailAccountForm form) {
		AdminRoleVerify.verify();
		Set<ConstraintViolation<EmailAccountForm>> failures = validator.validate(form);
		if(!failures.isEmpty()){
			return JSONResponse.invalid(failures);
		}
		
		EmailConfig config = new EmailConfig.Builder().useSMTP(form.isUseSMTP())
							.senderEmail(form.getSenderEmail())
							.smtpHost(form.getSmtpHost())
							.username(form.getUsername())
							.password(form.getPassword())
							.build();
		ConfigRepository.instance().put(config);
		return JSONResponse.successed();
	}
	
	//获取当前邮箱配置
	@RequestMapping(value="/config/emailAccount", method=RequestMethod.GET)
	public @ResponseBody JSONResponse getEmailAccount() throws JSONException{
		AdminRoleVerify.verify();
		EmailConfig config = ConfigRepository.instance().get(EmailConfig.class);
		return JSONResponse.successed(config);
	}
	
	//测试邮件帐号
	@RequestMapping(value="/config/emailAccount/test", method=RequestMethod.POST)
	public @ResponseBody JSONResponse testEmailAccount(@RequestParam String address){
		AdminRoleVerify.verify();
		//新建邮件
		SimpleEmail email = new SimpleEmail();
		email.setTo(new EmailAddress(address));
		//邮件主题
		String subject = "来自\"" + ConfigRepository.instance().get(SiteConfig.class).getSiteName() + "\"的测试邮件";
		email.setSubject(subject);
		email.setHtml("<font color=\"red\">" + subject + "</font>");
		
		if(sender.send(email)){
			return JSONResponse.successed();
		}
		return JSONResponse.errorMessage("发送邮件失败");
	}
	
	//获取站点配置
	@RequestMapping(value="/config/site", method=RequestMethod.GET)
	public @ResponseBody JSONResponse getSiteConfig() throws JSONException{
		AdminRoleVerify.verify();
		
		SiteConfigForm form = new SiteConfigForm();
		SiteConfig config = ConfigRepository.instance().get(SiteConfig.class);
		form.setAdminEmail(config.getAdminEmail());
		form.setBaseURL(config.getBaseURL());
		form.setDescription(config.getDescription());
		form.setSiteName(config.getSiteName());
		
		return JSONResponse.successed(form);
	}
	
	//保存站点配置
	@RequestMapping(value="/config/site", method=RequestMethod.POST)
	public @ResponseBody JSONResponse saveSiteConfig(@RequestBody SiteConfigForm form){
		AdminRoleVerify.verify();
		
		Set<ConstraintViolation<SiteConfigForm>> failures = validator.validate(form);
		if(!failures.isEmpty()){
			return JSONResponse.invalid(failures);
		}
		
		SiteConfig config = new SiteConfig.Builder().baseURL(form.getBaseURL())
							.description(form.getDescription())
							.adminEmail(form.getAdminEmail())
							.siteName(form.getSiteName())
							.build();
		ConfigRepository.instance().put(config);
		return JSONResponse.successed();
	}
	
	private String hidePassword(String password){
		StringBuffer sb = new StringBuffer();
		for(int i=0; i<password.length(); i++){
			char ch = password.charAt(i);
			if(password.length() >= 6 && (i==0 || i==password.length()-1 || i==password.length()-2)){
				sb.append(ch);
				continue;
			} 
			
			if(password.length() < 6 && password.length() > 1 && i == 0){
				sb.append(ch);
				continue;
			}
			sb.append('*');
		}
		return sb.toString();
	}
	
}
